package com.cssy.yd.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicSkReturnDAO;
import com.cssy.yd.logic.dao.LogicSkReturnItemDAO;
import com.cssy.yd.logic.dao.LogicSoReturnDAO;
import com.cssy.yd.logic.entity.LogicSoReturnDO;
import com.cssy.yd.logic.entity.LogicSkReturnDO;
import com.cssy.yd.logic.entity.LogicSkReturnItemDO;
import com.cssy.yd.logic.service.ILogicSkReturnService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicSkReturnService")
public class LogicSkReturnServiceImpl implements ILogicSkReturnService {
	@Resource(name = "logicSkReturnDAO")
	private LogicSkReturnDAO logicSkReturnDAO;

	@Resource(name = "logicSkReturnItemDAO")
	private LogicSkReturnItemDAO logicSkReturnItemDAO;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicSoReturnDAO")
	private LogicSoReturnDAO logicSoReturnDAO;

	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicSkReturnDO> list = logicSkReturnDAO.find(scs);
		rs.setRecordCount(logicSkReturnDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i = logicSkReturnDAO.deleteLogicSkReturnDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer update(LogicSkReturnDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicSkReturnDAO.updateLogicSkReturnDO(t);
	}

	@Override
	public LogicSkReturnDO save(LogicSkReturnDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		t.setId(IDCodeTypeUtil.getId());
		logicSkReturnDAO.insertLogicSkReturnDO(t);
		return t;
	}

	@Override
	public LogicSkReturnDO findListById(String id) throws SyBaseException {
		return logicSkReturnDAO.findLogicSkReturnDOByPrimaryKey(id);
	}

	@Override
	public SearchResult findItemListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicSkReturnItemDO> list = logicSkReturnItemDAO.find(scs);
		rs.setRecordCount(logicSkReturnItemDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer deleteItem(String id) throws SyBaseException {
		Integer i = logicSkReturnItemDAO.deleteLogicSkReturnItemDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer updateItem(LogicSkReturnItemDO t) throws SyBaseException {
		return logicSkReturnItemDAO.updateLogicSkReturnItemDO(t);
	}

	@Override
	public LogicSkReturnItemDO saveItem(LogicSkReturnItemDO t) throws SyBaseException {
		t.setId(IDCodeTypeUtil.getId());
		logicSkReturnItemDAO.insertLogicSkReturnItemDO(t);
		return t;
	}

	@Override
	public List<LogicSkReturnItemDO> findItemListBytkid(String tkid)
			throws SyBaseException {

		return logicSkReturnItemDAO.finditembytkid(tkid);
	}

	@Override
	public Double findLastedDOByExample(SearchConditions scs)
			throws SyBaseException {
		return logicSkReturnDAO.findLastedDOByOricode(scs);
	}

	@Override
	public LogicSkReturnItemDO findItemListById(String id) throws SyBaseException {
		return logicSkReturnItemDAO.findLogicSkReturnItemDOByPrimaryKey(id);
	}

	@Override
	public void skReturnSave(HttpServletRequest request, LogicSkReturnDO curAP)
			throws SyBaseException, SyCodeException {
		try {//新增草稿
			String tkDate = request.getParameter("tkDate");
			String itemdata = request.getParameter("itemdata");	
 			List<LogicSkReturnItemDO> itemlist = JSONArray.parseArray(itemdata, LogicSkReturnItemDO.class);	
 			// 检查是否已有此销售退货单的退款单草稿
			String oricode = request.getParameter("oriCode");
			SearchConditions scs = new SearchConditions();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus", "0", SearchCondition.OP_EQUAL);
			int tkcount = logicSkReturnDAO.count(scs);
			if(tkcount > 0){
				throw new SyBaseException("已有此销售退货的退款单草稿，请先处理已有的单据");
			}		
			 
				String id = IDCodeTypeUtil.getId();
				curAP.setId(id);
				curAP.setTkCode(syCodeService.getCode("SKTK","SKTK",SyCode.DATE_YYMM,5));
				String tkcode = curAP.getTkCode();
				curAP.setBillStatus(0);
				curAP.setRefundStatus(0);
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				if (tkDate != null && !"".equals(tkDate)) {
					curAP.setTkDate(DateUtils.stringToDate(tkDate));
				}	
				logicSkReturnDAO.insertLogicSkReturnDO(curAP);
				for (int i = 0; i < itemlist.size(); i++) {
					itemlist.get(i).setId(IDCodeTypeUtil.getId());
					itemlist.get(i).setTkid(id);
					itemlist.get(i).setTkcode(tkcode);
					logicSkReturnItemDAO.insertLogicSkReturnItemDO(itemlist.get(i));
				}
 			
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}
	
	@Override
	public void skReturnCommit(HttpServletRequest request, LogicSkReturnDO curAP)
			throws SyBaseException, SyCodeException {
		try {
			String tkDate = request.getParameter("tkDate");
			String itemdata = request.getParameter("itemdata");	
			String itemdelete = request.getParameter("itemdelete");
			String returnsocode = request.getParameter("oriCode");
 			List<LogicSkReturnItemDO> itemlist = JSONArray.parseArray(itemdata, LogicSkReturnItemDO.class);	
 			List<LogicSoReturnDO> soreturnlist = new ArrayList<LogicSoReturnDO>();
 			LogicSoReturnDO pd = null;
 			Double presthk = Double.parseDouble("0");  //本次实退货款
 			Double prewthk = Double.parseDouble("0"); //本次剩余未退货款
 			if (itemdelete != null && !"".equals(itemdelete)) {
				List<LogicSkReturnItemDO> srilist = JSONArray.parseArray(itemdelete, LogicSkReturnItemDO.class);
				for (LogicSkReturnItemDO srido : srilist) {
					if (srido.getId() != null&& !"".equals(srido.getId())) {
						logicSkReturnItemDAO.deleteLogicSkReturnItemDOByPrimaryKey(srido.getId());
					}
				}
			}
 			//提交收款退款单
 			if(itemlist != null && itemlist.size() > 0){
				for (LogicSkReturnItemDO skitem : itemlist) {
					skitem.setYthk((skitem.getYthk()==null ? 0 : skitem.getYthk()) + (skitem.getSthk()==null?0:skitem.getSthk()));
					skitem.setWthk((skitem.getWthk()==null ? 0 : skitem.getWthk()) - (skitem.getSthk()==null ? 0 : skitem.getSthk()));
					skitem.setSthk(skitem.getSthk()==null ? 0: skitem.getSthk());
					curAP.setYthk((curAP.getYthk()==null ? 0: curAP.getYthk()) + skitem.getSthk());
					presthk += skitem.getSthk();
					prewthk += skitem.getWthk();
				}
			}
			curAP.setBillStatus(2);
			SearchConditions scs = new SearchConditions();
			scs.addCondition("returnsocode", returnsocode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","3", SearchCondition.OP_EQUAL);
			soreturnlist = logicSoReturnDAO.find(scs);
			if(soreturnlist!=null&&soreturnlist.size()>0){ //取得对应的销售退货单
				pd = soreturnlist.get(0);
			}
 			SearchConditions scs1 = new SearchConditions();
			scs1.addCondition("oricode", returnsocode, SearchCondition.OP_EQUAL);
			scs1.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
 			Double hisythk = logicSkReturnDAO.findLastedDOByOricode(scs1);//最近一次退款后的已退金额		
 			Double hiswthk = new Double("0.0");
 			
 			if(hisythk == null||hisythk==0){
 				hisythk = Double.parseDouble("0.0");
 			}
 			hiswthk = new BigDecimal(curAP.getAmount().toString()).subtract(new BigDecimal(hisythk.toString())).doubleValue(); //最近一次收款后的未收金额
 			if(presthk.doubleValue() < hiswthk.doubleValue()) {
 				curAP.setRefundStatus(1);
 				if(pd.getId()!=null){
 					pd.setRefundStatus(1);  //根据收款情况改变销售出库单中的付款状态
 				}
 			} else if(presthk.doubleValue() == hiswthk.doubleValue()){
 				curAP.setRefundStatus(2);
 				if(pd.getId()!=null){
 					pd.setRefundStatus(2);
 				}
 			} else if(presthk.doubleValue() > hiswthk.doubleValue()) {
 				throw new SyBaseException("您本次退款大于退款单历史未退款！");
 			}
 			
 			int j = logicSoReturnDAO.updateLogicSoReturnDO(pd);
			if(j < 0){
				throw new SyBaseException("提交失败");
			}
			if (tkDate != null && !"".equals(tkDate)) {
				curAP.setTkDate(DateUtils.stringToDate(tkDate));
			}	
			
			curAP.setDuuser(SessionUtil.getUser(request).getName());
			curAP.setDutime(new Date());
			logicSkReturnDAO.updateLogicSkReturnDO(curAP);
			for (int i = 0; i < itemlist.size(); i++) {
				logicSkReturnItemDAO.updateLogicSkReturnItemDO(itemlist.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}

}
